package org.ww.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.ww.common.utils.PageUtils;
import org.ww.common.utils.Query;
import org.ww.common.utils.R;
import org.ww.ware.dao.WareInfoDao;
import org.ww.ware.entity.WareInfoEntity;
import org.ww.ware.feign.MemberFeignService;
import org.ww.ware.service.WareInfoService;
import org.ww.ware.vo.FareVo;
import org.ww.ware.vo.MemberAddressVo;

import java.math.BigDecimal;
import java.util.Map;


@Service("wareInfoService")
public class WareInfoServiceImpl extends ServiceImpl<WareInfoDao, WareInfoEntity> implements WareInfoService {

    @Autowired
    private MemberFeignService memberFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WareInfoEntity> page = this.page(
                new Query<WareInfoEntity>().getPage(params),
                new QueryWrapper<WareInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByParams(Map<String, Object> params) {
        LambdaQueryWrapper<WareInfoEntity> wrapper = Wrappers.lambdaQuery();
        String key = (String) params.get("key");
        if(StringUtils.isNotBlank(key)){
            wrapper.and(w -> {
                w.eq(WareInfoEntity::getId,key)
                        .or()
                        .like(WareInfoEntity::getAddress,key)
                        .or()
                        .like(WareInfoEntity::getAreacode,key);
            });
        }
        IPage<WareInfoEntity> page = this.page(
                new Query<WareInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public FareVo getFare(Long addrId) {
        FareVo vo = new FareVo();
        R r = memberFeignService.addrInfo(addrId);
        MemberAddressVo memberAddressVo = r.getData("memberReceiveAddress",new TypeReference<MemberAddressVo>() {
        });
        if(ObjectUtils.isNotEmpty(memberAddressVo)){
            String phone = memberAddressVo.getPhone();
            String fare = phone.substring(phone.length() - 1);
            vo.setFare(new BigDecimal(fare));
            vo.setAddress(memberAddressVo);
            return vo;
        }
        return null;
    }

}